package org.ly817.my.spring.core.context;

import org.ly817.my.spring.core.ioc.bean.BeanDefinition;
import org.ly817.my.spring.core.ioc.bean.reader.XmlBeanDefinitionReader;
import org.ly817.my.spring.core.ioc.factory.AbstractBeanFactory;
import org.ly817.my.spring.core.ioc.factory.AutowireCapableBeanFactory;
import org.ly817.my.spring.core.ioc.io.ResourceLoader;

import java.util.Map;

/**
 * Created by LuoYu on 2018/4/14.
 */
public class ClassPathApplicationContext extends AbstractApplicationContext {

    private String configLocation;

    public ClassPathApplicationContext(String configLocation) throws Exception {
        this(new AutowireCapableBeanFactory(), configLocation);
    }

    public ClassPathApplicationContext(AbstractBeanFactory beanFactory, String path) throws Exception {
        super(beanFactory);
        this.configLocation = path;
        refresh();
    }

    @Override
    protected void loadBeanDefinitions(AbstractBeanFactory beanFactory) throws Exception {
        XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(new ResourceLoader());
        xmlBeanDefinitionReader.loadBeanDefinitions(configLocation);
        for (Map.Entry<String, BeanDefinition> beanDefinitionEntry : xmlBeanDefinitionReader.getRegistry().entrySet()) {
            beanFactory.registerBeanDefinition(beanDefinitionEntry.getKey(), beanDefinitionEntry.getValue());
        }
    }
}
